package org.chaiyi.template.core.register.contractor.proxy;

import lombok.extern.slf4j.Slf4j;
import org.chaiyi.template.core.common.common.BeanNameManage;
import org.chaiyi.template.core.common.contract.ContractInfo;
import org.chaiyi.template.core.common.contract.ContractUtil;
import org.chaiyi.template.core.common.contract.Contractor;
import org.chaiyi.template.core.framework.mongo.Repository;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 为Contractor动态代理生成
 */
@Slf4j
@Component
public class ContractorGenerate implements BeanPostProcessor, ApplicationContextAware {
    private ApplicationContext applicationContext;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (!(bean instanceof Contractor)) {
            return bean;
        }
        Class<?> iService = ContractUtil.getIService(bean);
        String contractInfoName = BeanNameManage.getContractInfoName(iService);

        ContractInfo contractInfo = applicationContext.getBean(contractInfoName, ContractInfo.class);
        Repository repository = applicationContext.getBean(contractInfo.getRepositoryName(), Repository.class);


        return new ContractorProxyFactory<>(repository, contractInfo.getSupporter(), contractInfo.getEntity())
                .getProxy(bean);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}
